import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Index from '../views/Index.vue'
import Home from '../views/sys/Home.vue'
import { getMenuTree } from "@/api/menu/menu";
import store from "../store";
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login
  },
  {
    path: '/index',
    name: 'Index',
    component: Index,
    children: [
      {
        path: "/home",
        name: "Home",
        component: Home,
      }
    ]
  },
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  let hasRoute = store.state.menus.hasRoute;
  let token = sessionStorage.getItem("token");
  console.log(hasRoute);
  if (to.path == '/' || to.path == '') {
    next()
  } else if (!token) {
    next({ path: "/" })
  } else if (!hasRoute) {
    console.log(hasRoute);
    getMenuTree().then(res => {
      //菜单列表
      store.commit("setMenuList", res.data);
      //权限
      //store.commit("setPermList", res.data);
      let oldRoutes = router.options.routes;
      //已存在的路由
      res.data.forEach(menu => {
        if (menu.children) {
          menu.children.forEach(e => {
            //转换路由
            let route = menuToRoute(e)
            if (route) {
              oldRoutes.forEach(element => {
                if (element.name === "Index") {
                  element.children.push(route);
                }
              });
            }
            //添加到路由管理
          })
        }
      })
      console.log(oldRoutes);
      router.addRoutes(oldRoutes);
    })
    hasRoute = true;
    store.commit('changeRouteStatus', hasRoute)
  }
  next();
})
const menuToRoute = (menu) => {
  if (!menu.menuRoute) {
    return null
  }
  let route = {
    name: menu.menuName,
    path: menu.path,
  }
  route.component = () => import('@/views' + menu.menuRoute + '.vue');
  return route;
}
export default router
